/**
 * 
 */
package com.feib.stms.security.core.userdetails;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.feib.stms.model.User;
import com.feib.stms.service.UserService;

/**
 * @author Jimmy Liu
 *
 */
public class StmsUserDetailService implements UserDetailsService, InitializingBean {

	protected Logger logger = LoggerFactory.getLogger(this.getClass());
	
	public static final String USERNAME_SPLIT_FORMAT = "_conjunction_";
	
	private UserService userService;

	/**
	 * @param username 以'_conjunction_' 串接 群組代號與使用者帳號, ex:TPE001_conjunction_jimmyliu,代表使用者帳號為jimmyliu, 群組代號為TPE001
	 */
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException 
	{
		String[] userNameTemp = username.split(USERNAME_SPLIT_FORMAT);
		
		if (2 != userNameTemp.length){
            String message = "username formate is illegal!! (groupno"+USERNAME_SPLIT_FORMAT+"userId)";
            logger.info(message);
            throw new UsernameNotFoundException(message);
        }
    	
    	String groupNo = userNameTemp[0];// 群組代號
        String userId = userNameTemp[1]; // 使用者帳號
        

        // 取得用戶的密碼
        User user = userService.findLoginDataByUserIdGroupNo(userId, groupNo);
        
        if (null == user) {
            String message = "群組代號  : " + groupNo + "，使用者名稱 : " + userId + "不存在!!";
            logger.info(message);
            throw new UsernameNotFoundException(message);
        }
        
        StmsUserDetailsWrapper userWrapper = new StmsUserDetailsWrapper(user);
        
        /*
        if (null == userWrapper) {
            logger.debug("Query returned no results for user '" + username + "'");

            throw new UsernameNotFoundException( "Username " + username + " not found");
        }
        */
        
        addCustomAuthorities(username, userWrapper);
        
        if (userWrapper.getAuthorities().size() == 0) {
            logger.debug("User '" + username + "' has no authorities and will be treated as 'not found'");
            
            throw new UsernameNotFoundException( "Username " + username + " has no GrantedAuthority");
        }
        
		return userWrapper;
	}
	
	/**
	 * Allows subclasses to add their own granted authorities to the list to be returned in the <tt>UserDetails</tt>
	 * @param username
	 * @param user
	 */
	protected void addCustomAuthorities(String username, UserDetails user) {}

	
	/**
	 * @param userService 的設定的 userService
	 */
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public void afterPropertiesSet() throws Exception {
		if (userService == null ) {
            throw new IllegalArgumentException("UserService is required");
        }	
	}

}
